package com.common.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.Scroller;

import com.common.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 滑动删除的控件
 */
public class ItemSwipe extends FrameLayout {

    /**
     * 用于记录生成了多少控件，为了达到listview中点中一个，其余滑动控件自动关闭
     */
    private static final List<WeakReference<ItemSwipe>> OPENING_SCROLLER = new ArrayList<>();

    private static final int ANIMATION_DURATION = 500;//默认滑动动画时间
    private static final int MIN_LIMIT = 5;//最小滑动距离，同时也作为点击事件的触发基础

    private WeakReference<ItemSwipe> mThisReference = null;
    private View deleteView = null;
    private Scroller scroller;
    private boolean onTouching = false, scrollerEnable = true, isOpen = false;
    private float oX = 0, oY = 0, scrollerScale = 0.168f;//默认大概所需滑出控件的1/6大小多一些就可以滑出
    private int limit = 0;
    private int startX = 0, deleteWidth = 0;
    //private long mPressTime = 0;//按下的时间
    private boolean mLongClicked = false, mIsMoving = false;
    private Handler mPressHandler = new Handler(Looper.getMainLooper());
    private Runnable mPressRunnable = new Runnable() {
        @Override
        public void run() {
            if (onTouching && !mIsMoving) {
                mLongClicked = performLongClick();
                onTouching = false;
            } else {
                mLongClicked = false;
            }
        }
    };

    public ItemSwipe(Context context) {
        this(context, null);
    }

    public ItemSwipe(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (attrs != null) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ItemSwipe);
            limit = array.getDimensionPixelOffset(R.styleable.ItemSwipe_scrollerLimit, limit);
            scrollerScale = array.getFloat(R.styleable.ItemSwipe_scrollerScale, scrollerScale);
            scrollerEnable = array.getBoolean(R.styleable.ItemSwipe_scrollerEnable, scrollerEnable);
            array.recycle();
        }
        scroller = new Scroller(context);
        startX = scroller.getStartX();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (deleteView != null) {
            LayoutParams params = (LayoutParams) deleteView.getLayoutParams();
            int leftMargin = 0, topMargin = 0;
            if (params != null) {
                leftMargin = params.leftMargin;
                topMargin = params.topMargin;
            }
            int cl, cr, ct, cb;
            cl = getMeasuredWidth() - getPaddingRight() + leftMargin;
            cr = cl + deleteView.getMeasuredWidth();
            ct = getPaddingTop() + topMargin;
            cb = ct + deleteView.getMeasuredHeight();
            deleteView.layout(cl, ct, cr, cb);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        for (int index = 0, count = getChildCount(); index < count; index++) {
            View view = getChildAt(index);
            LayoutParams params = (LayoutParams) view.getLayoutParams();
            if (params.isOutside) {
                deleteView = view;
                deleteWidth = view.getMeasuredWidth();
                if (limit == 0) {
                    limit = (int) (deleteWidth * scrollerScale);
                }
                if (limit < MIN_LIMIT) {
                    limit = MIN_LIMIT;
                }
                break;
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        mPressHandler.removeCallbacks(mPressRunnable);
        super.onDetachedFromWindow();
        OPENING_SCROLLER.remove(new WeakReference<ItemSwipe>(this));
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (!isScrollerEnable()) {
            closeAll(this);
            //当滑动不启用时，返回默认方法
            return super.dispatchTouchEvent(event);
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //mPressTime = System.currentTimeMillis();
                onTouching = true;
                mIsMoving = false;
                oX = event.getRawX();
                oY = event.getRawY();
                mPressHandler.removeCallbacks(mPressRunnable);
                mPressHandler.postDelayed(mPressRunnable, 500);
                closeAll(this, null);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                onTouching = false;
                final float cX = event.getRawX();
                if (deleteView != null) {
                    final float internalX = cX - oX;
                    if (Math.abs(internalX) < MIN_LIMIT) {
                        final float cY = event.getRawY();
                        final float internalY = cY - oY;
                        if (Math.abs(internalY) < MIN_LIMIT) {
                            final boolean clicked = performClickOnThisZone(cX, cY);
                            close(clicked ? ANIMATION_DURATION : 0);
                            mLongClicked = false;
                            return clicked;
                        } else {
                            mIsMoving = true;
                            close();
                        }
                    } else if (internalX < -limit) {//cX - oX > 0 <--
                        mIsMoving = true;
                        open();
                    } else if (internalX > limit) {//cX - oX > 0 -->
                        mIsMoving = true;
                        close();
                    } else {
                        mIsMoving = true;
                        closeAll(this);
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                onTouching = true;
                mIsMoving = true;
                closeAll(this);
                break;
            default:
                onTouching = false;
                closeAll(null);
                break;
        }
        return onTouching || super.dispatchTouchEvent(event);
    }

    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), 0);
            postInvalidate();
        }
    }

    public boolean isOpen() {
        return isOpen;
    }

    public boolean isScrollerEnable() {
        return scrollerEnable;
    }

    public void open() {
        open(ANIMATION_DURATION);
    }

    public void open(int duration) {
        if (isOpen) {
            return;
        }
        scroller.startScroll(startX, scroller.getCurrY(), deleteWidth, 0, duration);
        isOpen = true;
        invalidate();
        if (mThisReference == null) {
            mThisReference = new WeakReference<ItemSwipe>(this);
        }
        OPENING_SCROLLER.add(mThisReference);
    }

    public void close() {
        close(ANIMATION_DURATION);
    }

    public void close(int duration) {
        if (!isOpen) {
            return;
        }
        scroller.startScroll(deleteWidth, scroller.getCurrY(), -deleteWidth, 0, duration);
        isOpen = false;
        invalidate();
        OPENING_SCROLLER.remove(mThisReference);
        if (mThisReference != null) {
            mThisReference.clear();
        }
        mThisReference = null;
    }

    public static void closeAll(ItemSwipe except) {
        closeAll(except, null);
    }

    public static void dispatchTouchEventOnActivity(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
            closeAll(null, ev);
        }
    }

    /**
     * 关闭其他
     *
     * @param event  事件，不为null时，在事件以内的不关闭
     * @param except 排除, null = 不排除
     */
    public static void closeAll(ItemSwipe except, MotionEvent event) {
        for (WeakReference<ItemSwipe> reference : OPENING_SCROLLER) {
            ItemSwipe scroller = reference.get();
            if (scroller != null && scroller.isOpen && (except == null || scroller != except)) {
                if (event != null) {
                    final int[] location = new int[2];
                    scroller.getLocationOnScreen(location);
                    if (location[0] > event.getRawX()
                            || event.getRawX() > location[0] + scroller.getWidth()
                            || location[1] > event.getRawY()
                            || event.getRawY() > location[1] + scroller.getHeight()) {
                        scroller.close();
                    }
                } else {
                    scroller.close();
                }
            }
        }
    }

    /**
     * 执行了点击事件，开始判断被点中的到底是哪个。
     * <br/>逻辑：
     * <p>1.递归向其内部子View传递点击事件，如果(x,y)刚好在内部控件上，且其内部控件有点击事件，则认为点击事件被其消耗，停止传递</p>
     * <p>2.当递归内部子View结束，依然没有消耗掉事件，则尝试{@link #performClick()}，如果被消耗，则停止传递</p>
     * <p>3.当2执行完毕后依然没有消耗掉点击事件，则向外部ViewGroup递归传递点击，传到没有外部或外部为AbsListView，或者外部设置了点击事件为止</p>
     *
     * @param x
     * @param y
     * @return 本方法如果返回false，是已经被消耗了点击事件，因为我内部用了‘!/非’。与系统方法相反
     */
    private boolean performClickOnThisZone(float x, float y) {
        return !mLongClicked
                && !loopTranslateClickToChild(this, x, y)
                && !performClick()
                && !loopTranslateClickToParent(this)
                ;
    }

    /**
     * 向外部ViewGroup递归传递点击，传到没有外部或外部为AbsListView，或者外部设置了点击事件为止
     *
     * @param view 当前View
     */
    private boolean loopTranslateClickToParent(View view) {
        ViewParent viewParent = view.getParent();
        ViewGroup parent = null;
        if (viewParent instanceof ViewGroup) {
            parent = (ViewGroup) viewParent;
        }
        if (parent == null) {
            return false;
        }
        boolean result = false;
        if (parent instanceof AbsListView) {
            AbsListView listView = (AbsListView) parent;
            int position = listView.getPositionForView(view);
            if (position != AbsListView.INVALID_POSITION) {
                result = result || listView.performItemClick(view, position, listView.getItemIdAtPosition(position));
            }
        } else if (!parent.performClick()) {
            result = result || loopTranslateClickToParent(parent);
        }
        return result;
    }

    /**
     * 递归向其内部子View传递点击事件，如果(x,y)刚好在内部控件上，且其内部控件有点击事件，则认为点击事件被其消耗，停止传递
     *
     * @param parent
     * @return
     */
    private boolean loopTranslateClickToChild(ViewGroup parent, float x, float y) {
        if (parent == null) {
            return false;
        }
        final int count = parent.getChildCount();
        for (int index = 0; index < count; index++) {
            final View child = parent.getChildAt(index);
            final int[] location = new int[2];
            child.getLocationOnScreen(location);
            final int l = location[0], r = l + child.getWidth(), t = location[1], b = t + child.getHeight();
            if (child instanceof ViewGroup) {
                ViewGroup nextGenerationsParent = (ViewGroup) child;
                if (loopTranslateClickToChild(nextGenerationsParent, x, y)) {
                    return true;
                }
                if (child.getVisibility() == VISIBLE && l <= x && x <= r && t <= y && y <= b && child.performClick()) {
                    return true;
                }
            } else if (child.getVisibility() == VISIBLE && l <= x && x <= r && t <= y && y <= b && child.performClick()) {
                return true;
            }
        }
        return false;
    }

    public void setScrollerEnable(boolean scrollerEnable) {
        this.scrollerEnable = scrollerEnable;
        if (!scrollerEnable) {
            close(0);
        }
    }

    public void setScrollerScale(float scrollerScale) {
        this.scrollerScale = scrollerScale;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new LayoutParams(p);
    }

    public static class LayoutParams extends FrameLayout.LayoutParams {
        public boolean isOutside = false;

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            if (attrs != null) {
                TypedArray array = c.obtainStyledAttributes(attrs, R.styleable.ItemSwipe_Layout);
                isOutside = array.getBoolean(R.styleable.ItemSwipe_Layout_IamOutside, isOutside);
                array.recycle();
            }
        }

        public LayoutParams(int width, int height) {
            super(width, height);
        }

        public LayoutParams(ViewGroup.LayoutParams source) {
            super(source);
        }
    }
}